package avpc

import (
	"fmt"
	"io"
	"os"
	"sync"
	"time"

	"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
)

var DefaultClient Client

type Client struct {
	*vpc.Client
	Port string
}

// todo sync onece
func NewDefaultClient() *Client {
	client, err := vpc.NewClientWithAccessKey("Southwest08", "116706bb9a4e4857b626ce5055d29a4b", "90a1fc4cdbe34f9ebe75283dbe87a728")
	client.Domain = "175.155.64.67"
	client.GetConfig().Debug = true
	client.SetLogger("debug", "ajy", os.Stdout, "")

	client.SetConnectTimeout(100 * time.Second)
	port := "9698"
	if err != nil {
		panic(err)
	}

	DefaultClient = Client{Client: client, Port: port}

	return &Client{}
}

var once sync.Once

func InitDefaultClient(regionId, accessKeyId, accessKeySecret, domain, port string, debug bool, out io.Writer) (*Client, error) {
	var outerErr error
	once.Do(func() {
		client, err := vpc.NewClientWithAccessKey(regionId, accessKeyId, accessKeySecret)
		if err != nil {
			outerErr = fmt.Errorf("failed to create ECS client: %w", err)
			return
		}
		client.Domain = domain
		client.GetConfig().Debug = debug

		client.SetLogger("debug", "ajy", out, "")

		DefaultClient = Client{Client: client, Port: port}

	})
	return &DefaultClient, outerErr
}
